<?php

namespace App\Api\GoModule\Controllers;

use App\Api\Controllers\BaseController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;
use App\Http\Requests;
use App\Http\Requests\changeUserInfoRequest;
use JWTAuth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Session;
use Curl\Curl;;
use TopClient;
use ResultSet;
use RequestCheckUtil;
use TopLogger;
use AlibabaAliqinFcSmsNumSendRequest;
use Illuminate\Foundation\Testing\TestCase;
use Illuminate\Http\Response;
use App\Wechat;


class UserChangeInfoController extends BaseController
{


   /**
    *
    *Author : johannlai
    *@function 获取乘客信息
    *
    *@param $request
    *@return $data['head'], $data['sex'], $data['nickname']
    */

    public function getInfo(Request $request)
    {
         $token = JWTAuth::getToken();
	 $user = JWTAuth::toUser($token);
	 if(!$user){
             $result = $this->returnMsg('40005','用户未找到');
    	     return response()->json($result);
	 }
	 $data['head'] = $user['headimgurl'];
	 $data['nickname'] = $user['nickname'];
	 $data['sex'] = $user['sex'];
	 $data['userphone']=$user['tel'];
         $result = $this->returnMsg('200','ok',$data);
    	    return response()->json($result);
    }

    /**
    *
    *@author johannlai
    *@function 修改乘客昵称，性别
    *
    *@param $request
    */

    public function changeInfo(changeUSerInfoRequest $request)
    {
        $updateData['nickname'] = $request->input('nickname');
        $updateData['sex'] = $request->input('sex');
	if($updateData['nickname']==''|| $updateData['sex']=='' )
        {
 	    $result = $this->returnMsg('57006','nickname or sex is null');
    	    return response()->json($result);
	}
	 $token = JWTAuth::getToken();
	 $user = JWTAuth::toUser($token);
	//更新数据	
	DB::table('wechats')
	        ->where('openid',$user['openid'])
                ->update($updateData);
	 $result = $this->returnMsg('200','ok');
	 return response()->json($result);
    }
    /**
    *
    *#author johannlai
    *@function 解除绑定乘客手机
    *
    *@param $request
    */

/*
    public function unBindPhone(Request $request)
    {

        $updateData['tel'] = $request->input('tel');
        $updateData['num'] = $request->input('num');
     
	if( $updateData['tel']=='' )
        {
 	    $result = $this->returnMsg('57002','data is empty');
    	    return response()->json($result);
	}
 	 $token = JWTAuth::getToken();
         $user = JWTAuth::toUser($token);
	
      //如果需要解除,首先验证这个手机是否本人绑定的手机
        $userPhone=DB::table('wechats')
		->select('tel')
		->where('openid',$user['openid'])
		->first();
	$userPhone = ((array)$userPhone)['tel'];
        if($userPhone != $updateData['tel']){
             $result = $this->returnMsg('57003','需要解除的手机并非绑定手机','');
	     return response()->json($result);
        }



	      $num = $request->input('num');
	      $num = 'x'.strval($num);
		$value = Redis::hgetall($userPhone);
	     // $value = $request->session()->get($num, 'default');
	if ($value['num'] == $num)
        {
           $ip = $_SERVER['REMOTE_ADDR'];
             $session_ip = $value['lastip'];
             $session_tel = $value['tel'];
             if ($session_ip!=$_SERVER['REMOTE_ADDR']) {
               $result = $this->returnMsg('54003','NO PERMISSION');
             	 return response()->json($result);
             }
             if ($session_tel!=$updateData['tel']) {
               $result = $this->returnMsg('51002','DIFFERENT TEL');
             	return response()->json($result);
             }
            $token = JWTAuth::getToken();
	    $user = JWTAuth::toUser($token);
		        DB::table('wechats')
		          ->where('openid',$user['openid'])
		          ->update(['tel'=>'']);
		       // $request->session()->forget($num);
			Redis::del($userPhone);
		        $result = $this->returnMsg('200','ok');
	    return response()->json($result);
	}
        else
        {
	    $result = $this->returnMsg('57001','ERROR CODE');
            return response()->json($result);
	}
    }


   /**
     *@author johannlai
     *@function 发送验证码解除绑定手机并且set  session
     *@param tel
     *@return sms sending status
     */
/* 
    public function SendCodeToUnBind(Request $request)
    {
      $time = strtotime(date('Y-m-d H:i:s',time()));//integer
      $time = $time%10000;
      $tel = $request->input('tel');
     
 
      //如果需要解除,首先验证这个手机是否本人绑定的手机
       $token = JWTAuth::getToken();
       $user = JWTAuth::toUser($token);
       $userPhone =  DB::table('wechats')
		->select('tel')
		->where('openid',$user['openid'])
		->first();
	$userPhone = ((array)$userPhone)['tel'];
      if($userPhone != $tel){
           $result = $this->returnMsg('57003','需要解除的手机并非绑定手机','');
	   return response()->json($result);
      }

 
      $value = array ('lastip'=>$_SERVER['REMOTE_ADDR'],'tel'=>$tel);
      $num = 'x'.strval($time);$value['num'] = $num;
//      $request->session()->put($num, $value);
	Redis::hmset($userPhone,$value);
      //发送短信
      $result=UserChangeInfoController::message($time,$request['tel']);
      $result = $this->returnMsg('200',$result);
      return $result;
    }

     */





    /**
    *
    *
    *@function 修改乘客手机
    *
    *@param $request
    */

    public function changePhone(Request $request)
    {
	
       $token = JWTAuth::getToken();
       $user = JWTAuth::toUser($token);
	

        $updateData['tel'] = $request->input('tel');
        if( $updateData['tel']=='' )
        {
 	        $result = $this->returnMsg('57002','data is empty');
    	    return response()->json($result);
	}

	
	$sameTel = DB::table('wechats')
	               ->where('tel',$updateData['tel'])
		       ->first();
		
	if($sameTel){
	    $result = $this->returnMsg('57003','已经存在相同的手机号');
    	    return response()->json($result);

	}	
	
	      $num = $request->input('num');
	      $num = 'x'.strval($num);
	     //$value = $request->session()->get($num, 'default');
		$n = Redis::hget($request['tel'],'num');
		$value = Redis::hgetall($request['tel']);
	      if ($n == $num)
        {
           $ip = $_SERVER['REMOTE_ADDR'];
             $session_ip = $value['lastip'];
             $session_tel = $value['tel'];
             if ($session_ip!=$_SERVER['REMOTE_ADDR']) {
               $result = $this->returnMsg('54003','NO PERMISSION');
             	 return response()->json($result);
             }
             if ($session_tel!=$updateData['tel']) {
               $result = $this->returnMsg('51002','DIFFERENT TEL');
               return response()->json($result);
             }
            $token = JWTAuth::getToken();
	    $user = JWTAuth::toUser($token);
	    
	    $oldUserTel = $user['tel'];
	    //更新订单记录表中的数据
	    $updatePhone['userphone'] = $updateData['tel'];
	    DB::table('order_records')
		->where('userphone',$oldUserTel)
	        ->update($updatePhone);
	    DB::table('delivery_records')
		->where('userphone',$oldUserTel)
	        ->update($updatePhone);

	    //取出sadd里面的数据，更新为新的手机
	   $sinterUserPhones = Redis::sinter('userPhone');		 
	   foreach($sinterUserPhones AS $sinterUserPhone){
		if($sinterUserPhone == $oldUserTel){
		    Redis::srem('userPhone',$oldUserTel);
		    Redis::sadd('userPhone',$updateData['tel']);
		    //如果有正在进行的订单
		    if(Redis::hgetall('usecar:'.$oldUserTel)){
		    	Redis::rename('usecar:'.$oldUserTel,'usecar:'.$updateData['tel']);	
		    }
		}
	  }
	 

			DB::table('wechats')
		          ->where('openid',$user['openid'])
		          ->update($updateData);
		       // $request->session()->forget($num);
			Redis::del($num);
		  
		  $result = $this->returnMsg('200','ok');
	          return response()->json($result);

	      }
        else
        {
	    $result = $this->returnMsg('57001','ERROR CODE');
            return response()->json($result);
	}
    }
    /**
     *@author Arius
     *@function set a session for tel number checking
     *@param tel
     *@return sms sending status
     */
    public function sessionSet(Request $request)
    {

       $token = JWTAuth::getToken();
       $user = JWTAuth::toUser($token);

	$sameTel = DB::table('wechats')
	               ->where('tel',$request['tel'])
		       ->first();
		
	if($sameTel){
	    $result = $this->returnMsg('57003','已经存在相同的手机号');
    	    return response()->json($result);

	}	

      $time = strtotime(date('Y-m-d H:i:s',time()));//integer
      $time = $time%10000;
      $value = array ('lastip'=>$_SERVER['REMOTE_ADDR'],'tel'=>$request->input('tel'));
      $num = 'x'.strval($time);
      $value['num'] = $num;
    //  $request->session()->put($num, $value);
	$set = Redis::hmset($request['tel'],$value);Redis::expire($set,1800);
      $result=UserChangeInfoController::message($time,$request['tel']);
      $result = $this->returnMsg('200',$result);
      return $result;
    }

        /**
            *@author Arius
            *@function send sms combined with Alidayu
            *@param checking code ,sms number
            *@todo  ip update for Alidayu white list
            *                               */
        public function message($num,$tel){
        $c = new TopClient();
        $c->appkey = "23553742";  //  App Key的值 这个在开发者控制台的应用管理点击你添加过的应用就有了
        $c->secretKey = "170f0500f220c2b61a95c2e9065a6670"; //App Secret的值也是在哪里一起的 你点击查看就有了
        $req = new AlibabaAliqinFcSmsNumSendRequest();
        $req->setExtend(""); //这个是用户名记录那个用户操作
        $req->setSmsType("normal"); //这个不用改你短信的话就默认这个就好了
        $req->setSmsFreeSignName("滴达"); //这个是签名
        $req->setSmsParam("{'code':'".$num."'}"); //这个是短信签名
        $req->setRecNum($tel); //这个是写手机号码
        $req->setSmsTemplateCode("SMS_32485128"); //这个是模版ID 主要也是短信内容
        $resp = $c->execute($req);
        $resp = json_encode($resp);
        $resp = json_decode($resp);
        if(isset($resp->result)){
            if($resp->result->err_code == 0){
              $result = $this->returnMsg('200','OK');
              return response()->json($result);
            }
        }
            $result = $this->returnMsg('500',$resp);
            return response()->json($result);
        }




}
